package com.ecnu.web.controller.incubation;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ecnu.common.constant.Constants;
import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.utils.http.HttpUtils;
import com.ecnu.system.domain.IncubationFactory;
import com.ecnu.system.domain.IncubationFile;
import com.ecnu.system.service.IIncubationFactoryService;
import com.ecnu.system.service.IIncubationFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@RestController
@Api(tags = "二期_Ai对接")
@RequestMapping("/AiIncubation")
@Validated//用来校验controller参数带@notblack类似的注解
public class AIIncubationController extends BaseController {
    @Autowired
    private IIncubationFactoryService incubationFactoryService;
    @Autowired
    private IIncubationFileService incubationFileService;
    @Value("${ai.pdf.parse-status-url}")
    private String parseStatusUrl;

    @ApiOperation(value = "提交Ai评估")
    @PostMapping("/editAssess")
    public AjaxResult editAssess(@Valid @RequestBody List<String> incubationList) {
        List<String> collect = incubationFactoryService.selectAssess(incubationList);
        if (CollectionUtil.isNotEmpty(collect)) {
            Map<String, Object> fileList = incubationFileService.getFileList(collect);
        }

        return AjaxResult.success("推送成功");
    }

    @ApiOperation(value = "提交Ai提取")
    @PostMapping("/editExtract")
    public AjaxResult editExtract(@Valid @RequestBody List<String> incubationList) {
        List<String> collect = incubationFactoryService.selectExtract(incubationList);
        if (CollectionUtil.isNotEmpty(collect)) {
            Map<String, Object> fileList = incubationFileService.editExtract(collect);
            if (!CollectionUtil.isEmpty(fileList)) {
                if (fileList.get("IsSuccess").toString().equals("true")) {
                    //调整为原始的数据
//                System.out.println(maps);
                    logger.info("获取Ai评估结果成功",fileList.get("Message"));
                    //调整状态（修改为解析中）
                    incubationFactoryService.editList(collect);
                    AjaxResult success = AjaxResult.success("提交成功，稍等几分钟可查看数据");
                    return success;
                }
                logger.error("获取Ai评估结果失败",fileList.get("ErrorMsg"));

            }
        }

        return AjaxResult.success("当前选择的成果暂无需要提取");
    }

    @ApiOperation(value = "获取Ai评估结果")
    @GetMapping("/getAssess")
    public AtomicReference<Map<String, Object>> getAssess(@Valid String id) {
        //todo 获取Ai评估结果
        IncubationFactory byId = incubationFactoryService.getById(id);
        LambdaQueryWrapper<IncubationFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IncubationFile::getIncuId, id)
                .eq(IncubationFile::getDelFlag, "0")
                .eq(IncubationFile::getFileType, "1");
        List<IncubationFile> incubationFiles = incubationFileService.list(wrapper);
        AtomicReference<Map<String, Object>> map = new AtomicReference<>(new LinkedHashMap<>());
        incubationFiles.forEach(one -> {
            String url = parseStatusUrl+"/api/ApiPdf/parse-status";

            //名称处理
            try {

                String[] split = one.getUrl().split("/");
                String encodedFileName = URLEncoder.encode(split[6], StandardCharsets.UTF_8.toString());
                String s = HttpUtils.sendGet(url, "fileName=" +encodedFileName, Constants.UTF8);

                map.set(JSONObject.parse(s));
            } catch (UnsupportedEncodingException e) {
                logger.error("编码失败",e.getMessage());

            }
            //访问返回

        });
        return map;
    }

    @ApiOperation(value = "AI处理成功后处理中间表问题")
    @GetMapping("/editIncuPro")
    public AjaxResult editIncuPro(@Valid @NotBlank String incubationId) {
        return incubationFactoryService.editIncuPro(incubationId);
    }
}
